import { COMPANY_TAGS, COMPANY_TYPE, CompanyStatus } from '@/pages/constant';
import { getCompanyEeviewListApi, reviewCompanyApi } from '@/services/brand';
import useTableList from '@/utils/useTableList';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Space,
  Table,
  Tag,
  Image,
  Checkbox,
  Cascader,
  Descriptions,
} from 'antd';
import React, { useEffect, useState } from 'react';
import styles from './index.less';
import { ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import classNames from 'classnames';
import useAreas from '@/utils/useAreas';
import { findItem } from '@/utils/findItem';
import useCategory from '@/utils/useCategory';
import message from '@/utils/message';

const CompanyReview: React.FC = () => {
  const { loading, form, datasource, page, pageSize, total, onFinish, onPageChange } = useTableList(
    { fetchApi: getCompanyEeviewListApi, initValues: { statusList: [0] } },
  );
  const [editLoading, setEditLoading] = useState(false);
  const { areas } = useAreas();
  const { allCategoryList } = useCategory();
  const [reviewForm] = Form.useForm();
  const [currentData, setCurrentData] = useState<any>(null);
  const status = Form.useWatch('status', reviewForm);
  const onCancel = () => {
    setCurrentData(null);
  };

  useEffect(() => {
    if (currentData) {
      reviewForm.setFieldsValue({
        id: currentData.id,
        location: currentData.location,
        auditRemark: currentData.auditRemark,
      });
    } else {
      reviewForm.resetFields();
    }
  }, [currentData]);

  const onSave = async (values: any) => {
    setEditLoading(true);
    if (values.categoryIds) {
      values.categoryIds = values.categoryIds.map((v: any) => v.at(-1));
    }
    const { rsCode } = await reviewCompanyApi(values);
    setEditLoading(false);
    if (rsCode === '00000000') {
      onCancel();
      message.success('审核提交成功');
      onPageChange(page);
    }
  };

  const onOk = async () => {
    reviewForm
      .validateFields()
      .then((v: any) => {
        onSave(v);
      })
      .catch((e) => {
        console.log(e);
      });
  };

  const columns: ColumnsType<any> = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
      width: 100,
    },
    {
      title: '审核类型',
      dataIndex: 'registerType',
      key: 'registerType',
      width: 100,
      render: (type: number) => {
        return type === 0 ? '企业认领' : '企业入驻';
      },
    },
    {
      title: '公司/品牌名称',
      dataIndex: 'companyName',
      key: 'companyName',
      width: 150,
    },
    {
      title: '企业/工厂名称',
      dataIndex: 'factoryName',
      key: 'factoryName',
      width: 300,
    },
    {
      title: '企业类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: number) => {
        const item = COMPANY_TYPE.find((item) => item.value === type);
        if (item) {
          return <Tag color="green">{item.label}</Tag>;
        }
      },
    },
    {
      title: '企业标签',
      dataIndex: 'tags',
      key: 'tags',
      width: 300,
      render: (tags: any[]) => (
        <Flex align="center" justify="flex-start" gap={10}>
          {tags?.map((tag) => (
            <div className={classNames(styles.type_name, styles[`type_name_${tag}`])} key={tag}>
              {COMPANY_TAGS.find((item) => item.value === tag)?.label}
            </div>
          ))}
        </Flex>
      ),
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 150,
    },
    {
      title: '联系邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 200,
    },
    {
      title: '企业地址',
      dataIndex: 'address',
      key: 'address',
      width: 300,
      render: (_, company: any) =>
        `${findItem(areas, 'id', company.province)?.name || ''}${
          findItem(areas, 'id', company.city, 'children')?.name || ''
        }${company.address}`,
    },
    {
      title: '企业官网',
      dataIndex: 'website',
      key: 'website',
      width: 150,
      render: (website: string) =>
        website && (
          <a href={website} target="_blank" rel="noreferrer">
            {website}
          </a>
        ),
    },
    {
      title: '企业图片',
      dataIndex: 'pictureUrl',
      key: 'pictureUrl',
      width: 150,
      render: (url: string) => url && <Image src={url} width={'100%'} />,
    },
    {
      title: '企业产能',
      dataIndex: 'productionCapacity',
      key: 'productionCapacity',
      width: 100,
    },
    {
      title: '投产时间',
      dataIndex: 'sine',
      key: 'sine',
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      key: 'memo',
      width: 200,
    },
    {
      title: '供应客户',
      dataIndex: 'customer',
      key: 'customer',
      width: 200,
    },
    {
      title: '企业分类',
      dataIndex: 'categoryIds',
      key: 'categoryIds',
      width: 200,
      render: (categoryIds: number[]) =>
        categoryIds
          .map((v) => `${findItem(allCategoryList, 'id', v, 'children')?.name || ''}`)
          .join('，'),
    },
    {
      title: '产品或业务',
      dataIndex: 'product',
      key: 'product',
      width: 200,
    },
    {
      title: '其他需求',
      dataIndex: 'demand',
      key: 'demand',
      width: 200,
    },
    {
      title: '申请人信息',
      dataIndex: 'applyUserInfo',
      key: 'applyUserInfo',
      width: 300,
      render: (applyUserInfo: any) =>
        applyUserInfo ? (
          <Descriptions
            column={1}
            items={[
              {
                key: 'phone',
                label: '联系电话',
                children: applyUserInfo.phone,
              },
              {
                key: 'username',
                label: '用户名',
                children: applyUserInfo.username || '-',
              },
              {
                key: 'email',
                label: '邮箱',
                children: applyUserInfo.mail || '-',
              },
              {
                key: 'position',
                label: '职位',
                children: applyUserInfo.position || '-',
              },
            ]}
          />
        ) : (
          '-'
        ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 150,
      render: (status: number) => {
        if (status === 0) {
          return <Tag color="gray">待审核</Tag>;
        } else if (status === 1) {
          return <Tag color="green">已通过</Tag>;
        } else {
          return <Tag color="red">已拒绝</Tag>;
        }
      },
    },
    {
      title: '申请时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 200,
      render: (time: string) => {
        return dayjs(time).format('YYYY-MM-DD HH:mm:ss');
      },
    },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      width: 150,
      align: 'center',
      fixed: 'right',
      render: (_, row) => {
        return row.status !== 1 ? (
          <Space>
            <Button
              type="primary"
              size="small"
              onClick={() => {
                setCurrentData({ ...row });
              }}
            >
              审核
            </Button>
          </Space>
        ) : null;
      },
    },
  ];

  return (
    <PageContainer>
      <Row gutter={[30, 30]} style={{ padding: '15px 30px' }}>
        <div className={styles.search_box}>
          <Form
            form={form}
            onFinish={onFinish}
            onReset={() => onFinish({ statusList: [0] })}
            labelCol={{
              span: 5,
            }}
            style={{ width: '100%' }}
          >
            <Row gutter={[20, 20]}>
              <Col xs={24} sm={24} md={12} lg={12} xl={8} xxl={6}>
                <Form.Item label="状态" name="statusList" initialValue={[0]}>
                  <Select
                    options={[
                      {
                        label: '待审核',
                        value: 0,
                      },
                      {
                        label: '已通过',
                        value: 1,
                      },
                      {
                        label: '已拒绝',
                        value: 2,
                      },
                    ]}
                    placeholder="请选择"
                    allowClear
                    mode="multiple"
                  />
                </Form.Item>
              </Col>
              <Col xs={24} sm={24} md={12} lg={12} xl={16} xxl={18}>
                <Flex align="center" justify="flex-end" gap={15}>
                  <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
                    查询
                  </Button>
                  <Button htmlType="reset" icon={<ReloadOutlined />}>
                    重置
                  </Button>
                </Flex>
              </Col>
            </Row>
          </Form>
        </div>
        <div className={styles.table_box}>
          <Table
            columns={columns}
            dataSource={datasource}
            loading={loading}
            rowKey="id"
            scroll={{ x: 3800 }}
            pagination={{
              current: page,
              pageSize: pageSize,
              total: total,
              showSizeChanger: false,
              showQuickJumper: true,
              onChange: onPageChange,
              showTotal: (total) => `共 ${total} 条数据`,
            }}
          />
        </div>
      </Row>
      <Modal
        title="审核"
        centered
        width={600}
        open={!!currentData}
        onCancel={onCancel}
        onOk={onOk}
        okButtonProps={{ loading: editLoading }}
      >
        <Form
          form={reviewForm}
          labelCol={{ span: 5 }}
          wrapperCol={{ span: 18 }}
          style={{ padding: '20px 0' }}
        >
          <Form.Item label="ID" name="id" hidden />
          <Form.Item
            label="审核状态"
            name="status"
            rules={[{ required: true, message: '请选择审核状态' }]}
          >
            <Select
              placeholder="请选择审核状态"
              options={[
                {
                  label: '通过',
                  value: true,
                },
                {
                  label: '拒绝',
                  value: false,
                },
              ]}
            />
          </Form.Item>
          {status === true && (
            <>
              <Form.Item
                label="企业经纬度"
                name="location"
                rules={[{ required: true, message: '请输入企业经纬度' }]}
              >
                <Input placeholder="请输入企业经纬度" />
              </Form.Item>
              <Form.Item
                label="标签"
                name="tags"
                rules={[{ required: true, message: '请选择企业标签' }]}
                initialValue={[]}
              >
                <Checkbox.Group options={COMPANY_TAGS} />
              </Form.Item>
              <Form.Item
                label="所属行业"
                name="categoryIds"
                rules={[{ required: true, message: '请选择所属行业' }]}
              >
                <Cascader
                  placeholder="请选择分类标签"
                  options={allCategoryList}
                  allowClear
                  fieldNames={{
                    label: 'name',
                    value: 'id',
                    children: 'children',
                  }}
                  multiple
                />
              </Form.Item>
            </>
          )}
          <Form.Item
            label="审核备注"
            name="auditRemark"
            rules={status === false ? [{ required: true, message: '请输入审核备注' }] : []}
          >
            <Input.TextArea rows={4} placeholder="请输入审核备注" />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default CompanyReview;
